using Microsoft.Extensions.Logging;
using TaskScheduler.Core;
using TaskScheduler.Infrastructure.Services;

namespace TaskScheduler.Tasks;

/// <summary>
/// 每日报表任务示例
/// 生成每日报表并发送通知
/// </summary>
public class DailyReportTask : ITask
{
    private readonly ILogger<DailyReportTask> _logger;
    private readonly IFeishuService _feishuService;

    public DailyReportTask(
        ILogger<DailyReportTask> logger,
        IFeishuService feishuService)
    {
        _logger = logger;
        _feishuService = feishuService;
    }

    public string TaskName => "DailyReportTask";
    public string Description => "每日报表任务 - 每天早上9点执行";
    public bool IsEnabled => true;
    public string CronExpression => "0 9 * * *"; // 每天早上9点执行

    public async Task<TaskResult> ExecuteAsync(CancellationToken cancellationToken = default)
    {
        try
        {
            _logger.LogInformation("开始生成每日报表...");

            // 1. 收集统计数据
            var statistics = await CollectStatisticsAsync(cancellationToken);

            // 2. 生成报表
            var report = GenerateReport(statistics);
            _logger.LogInformation("报表生成完成");

            // 3. 发送通知
            await _feishuService.SendMessageAsync(
                "📊 每日数据报表",
                report
            );

            return new TaskResult
            {
                IsSuccess = true,
                Message = "每日报表生成并发送成功"
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生成每日报表失败");
            return new TaskResult
            {
                IsSuccess = false,
                Message = ex.Message,
                Exception = ex
            };
        }
    }

    /// <summary>
    /// 收集统计数据（示例）
    /// </summary>
    private async Task<Dictionary<string, int>> CollectStatisticsAsync(CancellationToken cancellationToken)
    {
        await Task.Delay(300, cancellationToken);

        // 这里是示例数据，实际使用时应该从数据库查询真实数据
        return new Dictionary<string, int>
        {
            ["总用户数"] = 1250,
            ["新增用户"] = 45,
            ["活跃用户"] = 892,
            ["订单数量"] = 156
        };
    }

    /// <summary>
    /// 生成报表内容
    /// </summary>
    private string GenerateReport(Dictionary<string, int> statistics)
    {
        var reportLines = new List<string>
        {
            $"日期: {DateTime.Now:yyyy-MM-dd}",
            new string('=', 30),
            ""
        };

        foreach (var (key, value) in statistics)
        {
            reportLines.Add($"{key}: {value:N0}");
        }

        return string.Join("\n", reportLines);
    }
}

